import axios from 'axios'
import Vue from 'vue'
import Vuex,{Store} from 'vuex'
import {nanoid} from 'nanoid'
Vue.use(Vuex)

export default new Store({
  actions:{
    // 奇数加
    oddAdd({commit,state},value){
      if(state.sum % 2){
        commit('ADD',value)
      }
    },
    // 异步加
    waitAdd({commit},value){
      setTimeout(() => {
        commit('ADD',value)
      }, 1000);
    },
    // 由服务器决定加几
    serverAdd({commit}){
      axios.get('https://api.uomg.com/api/rand.qinghua?format=json').then(
        response => {
          console.log(response.data.content)
          commit('ADD',response.data.content.length)
        },
        error => {
          console.log(error.message)
        }
      )
    },
    // 追加一个小狗
    addDog({commit}){
      axios.get('https://dog.ceo/api/breed/pembroke/images/random').then(
        response => {
          console.log(response.data.message)
          commit('ADD_DOG',{id:nanoid(),url:response.data.message})
        },
        error => {
          console.log(error.message)
        }
      )
    }
  },
  mutations:{
    ADD(state,value){
      state.sum += value
    },
    MINUS(state,value){
      state.sum -= value
    },
    ADD_DOG(state,dogObj){
      state.dogs.push(dogObj)
    }
  },
  state:{
    sum:1,
    school:'atguigu',
    address:'宏福科技园',
    dogs:[
      {id:'tyuaytsfd01',url:'https://images.dog.ceo/breeds/pembroke/n02113023_4373.jpg'}
    ]
  },
  getters:{
    bigSum(state){
      return state.sum * 10
    },
    bigSchool(state){
      return state.school.toUpperCase()
    },
  }
})
